<template>
  <div
    class="container box"
    style="padding: 20px; height: 92%; overflow-y: scroll"
  >
    <el-form label-width="80px" :model="newsContent" :rules="Rules">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="newsContent.title"
          size="small"
          width="200px"
        ></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="author">
        <el-input v-model="newsContent.author" size="small"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="标签" prop="label">
            <el-input v-model="newsContent.label" size="small"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分类" prop="type">
            <el-input v-model="newsContent.type" size="small"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="图片">
        <el-upload
          :httpRequest="httpRequest"
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="图片" style="display: none">
        <el-upload
          :httpRequest="httpRequest1"
          class="avatar-uploader1"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess1"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="新闻内容" prop="content">
        <quill-editor
          class="quill"
          v-model="newsContent.content"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        >
        </quill-editor>
      </el-form-item>
      <div class="demo-drawer__footer">
        <el-button type="primary" @click="submitContent()" size="mini"
          >保存</el-button
        >
      </div>
    </el-form>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [
    {
      header: 1,
    },
    {
      header: 2,
    },
  ], // custom button values
  [
    {
      list: "ordered",
    },
    {
      list: "bullet",
    },
  ],
  [
    {
      script: "sub",
    },
    {
      script: "super",
    },
  ], // superscript/subscript
  [
    {
      indent: "-1",
    },
    {
      indent: "+1",
    },
  ], // outdent/indent
  [
    {
      direction: "rtl",
    },
  ], // text direction

  [
    {
      size: ["small", false, "large", "huge"],
    },
  ], // custom dropdown
  [
    {
      header: [1, 2, 3, 4, 5, 6, false],
    },
  ],

  [
    {
      color: [],
    },
    {
      background: [],
    },
  ], // dropdown with defaults from theme
  [
    {
      font: [],
    },
  ],
  [
    {
      align: [],
    },
  ],
  ["link", "image"],
  ["clean"], // remove formatting button
];
export default {
  components: {
    quillEditor,
  },
  name: "outServiceManage",
  data() {
    return {
      imageUrl: "",
      newsContent: {
        content: "",
        title: "",
        author: "",
        label: "",
        type: "",
        attachmentList: [],
        attachmentList1: [],
      },
      editorOption: {
        placeholder: "请输入新闻内容",
        theme: "snow",
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector(".avatar-uploader1 input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      Rules: {
        title: [
          {
            required: true,
            message: "请输入文章标题",
            trigger: "blur",
          },
        ],
        author: [
          {
            required: true,
            message: "请输入发布人",
            trigger: "blur",
          },
        ],
        label: [
          {
            required: true,
            message: "请选择标签",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择分类",
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async handleDownLoad() {
      const res = await this.$http
        .get(
          `/${this.$ServiceName}/api/external/protected/file/onlineexternal?id=${this.imageId}`,
          {
            responseType: "arraybuffer",
            params: {
              token: window.sessionStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          // console.log(res.request.responseURL,'ressss')
          this.imageUrl = res.request.responseURL;
        })
        .catch((error) => {});
    },
    async handleDownLoad1(res1) {
      const res = await this.$http
        .get(
          `/${this.$ServiceName}/api/external/protected/file/onlineexternal?id=${this.imageId}`,
          {
            responseType: "arraybuffer",
            params: {
              token: window.sessionStorage.getItem("token"),
            },
          }
        )
        .then((res) => {
          // console.log(res.request.responseURL,'ressss')
          this.imageUrl1 = res.request.responseURL;
        })
        .catch((error) => {});
      // para.onSuccess(res)
      // this.imageUrl = URL.createObjectURL(file.raw);
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let vm = this;
      let quill = this.$refs.myQuillEditor.quill;
      console.log("res1---", vm.$refs.myQuillEditor.quill.getSelection());
      // 如果上传成功
      if (res1.status == "200") {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片 res.info为服务器返回的图片地址
        quill.insertEmbed(length, "image", this.imageUrl1);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        vm.$Message.error("图片插入失败");
      }
    },
    httpRequest(para) {
      let FormDatas = new FormData();
      FormDatas.append("fileArray", para.file);
      FormDatas.append("businessType", "14"); //文件夹名称
      this.$http
        .post(
          `/${this.$ServiceName}/api/external/protected/file/upload`,
          FormDatas
        )
        .then((res) => {
          this.$notify.success({
            title: "成功",
            message: "文件上传成功",
          });
          let list = res.data.data;
          this.imageId = res.data.data[0].fileId;
          this.fileName = res.data.data[0].fileName;
          // this.imageUrl = res.data.data[0].trueUrl
          list.forEach((el) => {
            this.newsContent.attachmentList1.push({
              fileName: el.fileName,
              fileId: el.fileId,
            });
          });
          this.handleDownLoad();
          // para.onSuccess(res)
        })
        .catch((error) => {});
    },
    httpRequest1(para) {
      let FormDatas = new FormData();
      FormDatas.append("fileArray", para.file);
      FormDatas.append("businessType", "14"); //文件夹名称
      this.$http
        .post(
          `/${this.$ServiceName}/api/external/protected/file/upload`,
          FormDatas
        )
        .then((res) => {
          this.$notify.success({
            title: "成功",
            message: "文件上传成功",
          });
          let list = res.data.data;
          this.imageId = res.data.data[0].fileId;
          this.fileName = res.data.data[0].fileName;
          this.handleDownLoad1(res);
          // this.imageUrl = res.data.data[0].trueUrl
          list.forEach((el) => {
            this.newsContent.attachmentList.push({
              fileName: el.fileName,
              fileId: el.fileId,
            });
          });
        })
        .catch((error) => {});
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess1(res, file) {
      console.log(res, "ewssss");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
    submitContent() {
      this.$http
        .post(
          `/psys-external-service/api/external/exnewsinfo/${this.$version}/insert`,
          this.newsContent
        )
        .then((res) => {
          this.$message.success("发布成功！");
          this.newsContent = {};
          this.imageUrl = "";
        })
        .catch((error) => {});
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.ql-container {
  height: 380px;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
}
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
